package m202406.d09;

import java.util.Arrays;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/9 12:07
 */
public class Q16 {

    public static void main(String[] args) {
        Q16 q16 = new Q16();
        q16.threeSumClosest(new int[]{4, 0, 5, -5, 3, 3, 0, -4, -5}, -2);
    }

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int best = Integer.MAX_VALUE;
        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            for (int second = first + 1, third = nums.length - 1; second < third; ) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    second++;
                    continue;
                }
                int temp = nums[first] + nums[second] + nums[third];
                if (temp == target) {
                    return temp;
                }
                if (Math.abs(temp - target) < Math.abs(best - target)) {
                    best = temp;
                }
                if (temp > target) {
                    third--;
                } else {
                    second++;
                }
            }
        }
        return best;
    }
}
